package com.dbsop.domain.rest.rank;

import com.dbsop.common.enums.Order;
import com.dbsop.domain.EsOrder;
import com.dbsop.domain.RankBean;
import com.dbsop.domain.Ranking;
import org.elasticsearch.index.query.InnerHitBuilder;
import org.elasticsearch.search.collapse.CollapseBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;

import java.util.ArrayList;
import java.util.List;

/**
 * 排名
 */
public class RestRanking extends Ranking {

    /**
     * 需要进行折叠的字段
     */
    private String groupField;

    private List<RankBean> rankBeanList;


    public RestRanking(String groupField, List<RankBean> rankBeanList) {
        this.groupField = groupField;
        this.rankBeanList = rankBeanList;
    }

    public RestRanking(String groupField, RankBean rankBean) {
        this.groupField = groupField;
        this.rankBeanList = new ArrayList<RankBean>(1);
        this.rankBeanList.add(rankBean);
    }

    /**
     * 排名条件设置
     * @return
     */
    public  CollapseBuilder getBuilder(){
        if (rankBeanList == null || rankBeanList.size() == 0){
            return null;
        }
        CollapseBuilder collapseBuilder = new CollapseBuilder(groupField);
        List<InnerHitBuilder> innerHitBuilders = new ArrayList<InnerHitBuilder>();
        for (RankBean rankBean : rankBeanList) {
            InnerHitBuilder innerHitBuilder = new InnerHitBuilder();
            List<EsOrder> esOrderList = rankBean.getEsOrderList();

            for (EsOrder esOrder : esOrderList) {
                List<String> fields = esOrder.getFields();
                Order order = esOrder.getOrder();
                for (String field : fields) {
                    FieldSortBuilder fieldSortBuilder = new FieldSortBuilder(field);
                    switch (order){
                        case ASC:
                            fieldSortBuilder.order(SortOrder.ASC);
                            break;
                        case DESC:
                            fieldSortBuilder.order(SortOrder.DESC);
                            break;
                    }
                    innerHitBuilder.addSort(fieldSortBuilder);
                }
                // 进行数量设置
                innerHitBuilder.setSize(rankBean.getSize());
                // 进行折叠名称设置
                innerHitBuilder.setName(rankBean.getFlagName());
                innerHitBuilders.add(innerHitBuilder);
            }
            collapseBuilder.setInnerHits(innerHitBuilders);
        }
        return  collapseBuilder;
    }
}
